#include "stdio.h"
#include "unistd.h"
#include "sys/time.h"
#include "pthread.h"
#include "stdlib.h"

void *num_sqr(void *args)
{
    sleep(1);
    int *num = (int *)args;
    printf("num = %d \n",*num);
    int *result = malloc(sizeof(int));

    *result = (*num) * (*num);

    return result;
}

int main(int argc, char const *argv[])
{
    int nums[5] = {1, 2, 3, 4, 5};

    struct timeval start, end;

    gettimeofday(&start, NULL);
    int sum = 0;

    // 创建集合用于存放多个线程操作句柄
    pthread_t pts[5];

    for (int i = 0; i < 5; i++)
    {
        // 创建线程完成计算平方
        pthread_create(&pts[i], NULL, num_sqr, &nums[i]);
    }

    // 从每个线程中获取单独的计算结果并累加
    for (int i = 0; i < 5; i++)
    {
        // 该函数不仅可以获取分线程返回值,还具备等待的作用
        void *result;
        pthread_join(pts[i], &result);
        sum += *(int *)result;

        // 释放分线程函数的返回值
        free(result);
    }

    gettimeofday(&end, NULL);

    printf("平方和 Sum = %d \n", sum);
    printf("计算总时长为:%ld \n", end.tv_sec - start.tv_sec);

    return 0;
}
